package com.yima.baseproj.module.app.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.yima.baseproj.module.app.Controller.model.QueryModel;
import com.yima.baseproj.module.app.equipmentDevice.EquipmentDeviceEntity;
import com.yima.baseproj.module.app.equipmentDevice.EquipmentDeviceService;
import com.yima.baseproj.module.app.equipmentEquipment.EquipmentEquipmentEntity;
import com.yima.baseproj.module.app.equipmentEquipment.EquipmentEquipmentService;
import com.yima.baseproj.module.app.gentable.util.StringUtils;
import com.yima.baseproj.security.annotation.SecurityIgnoreUrl;
import com.yima.baseproj.utils.CacheUtil;
import com.yima.baseproj.utils.Error.MessageConstant;
import com.yima.baseproj.utils.HttpClientUtil;
import com.yima.baseproj.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

import static com.yima.baseproj.utils.JsonUtils.settingUpdateJson;

@Api(tags = "接收")
@RequestMapping("/api/app/reception")
@RestController
public class receptionController {
    private static final String PROJECT_GUID = "52A5A9157E3942AE830EFC1D6AB2A86F";
    @Autowired
    private EquipmentDeviceService equipmentDeviceService;
    @Resource
    private EquipmentEquipmentService equipmentEquipmentService;

    @ApiOperation("鉴权接口")
    @PostMapping(value = "/event")
    @SecurityIgnoreUrl(isNeedResultVo = false)
    public void authentication(String eventGuid, String eventCode, String eventMsg) throws Exception {
        if (StringUtils.isBlank(eventMsg)) {
            // 当eventMsg为空时，可以给设备实体类赋默认值或空值
            eventMsg = "{}";
        }
        JSONParser parser = new JSONParser();
        JSONObject jsonObject = (JSONObject) parser.parse(eventMsg);
        Map<String, Object> map = jsonObject;
        EquipmentDeviceEntity equipmentDeviceEntity = new EquipmentDeviceEntity();
        String deviceNo = (String) map.get("deviceNo");
        equipmentDeviceEntity.setEventCode(eventCode);
        equipmentDeviceEntity.setEventGuid(eventGuid);
        equipmentDeviceEntity.setDeviceNo(deviceNo);
        Long type = (Long) map.get("type");
        equipmentDeviceEntity.setDeviceIp((String) map.get("deviceIp"));
        equipmentDeviceEntity.setAdmitGuid((String) map.get("admitGuid"));
        equipmentDeviceEntity.setRecMode((String) map.get("recMode"));
        equipmentDeviceEntity.setFilePath((String) map.get("filePath"));
        equipmentDeviceEntity.setShowTime((Long) map.get("showTime"));
        equipmentDeviceEntity.setAliveType((Long) map.get("aliveType"));
        equipmentDeviceEntity.setRecScore((Long) map.get("recScore"));
        equipmentDeviceEntity.setDeviceVersion((String) map.get("deviceVersion"));
        equipmentDeviceEntity.setSource((Long) map.get("source"));
        equipmentDeviceEntity.setType(type);
        equipmentDeviceEntity.setCardNo((String) map.get("cardNo"));
        equipmentDeviceEntity.setDeviceName((String) map.get("deviceName"));
        equipmentDeviceEntity.setRecType((Long) map.get("recType"));
        equipmentDeviceEntity.setPermissionTimeType((Long) map.get("permissionTimeType"));
        equipmentDeviceEntity.setPassTimeType((Long) map.get("passTimeType"));
        equipmentDeviceEntity.setRecModeType((Long) map.get("recModeType"));
        equipmentDeviceEntity.setStorageId((String) map.get("storageId"));
        equipmentDeviceEntity.setTimestamp((Long) map.get("timestamp"));
        equipmentDeviceEntity.setAdmitName((String) map.get("admitName"));
        equipmentDeviceEntity.setCardinfoName((String) map.get("cardinfoName"));
        equipmentDeviceEntity.setCardinfoSex((String) map.get("cardinfoSex"));
        equipmentDeviceEntity.setCardinfoIdnum((String) map.get("cardinfoIdnum"));
        equipmentDeviceEntity.setCardinfoAddress((String) map.get("cardinfoAddress"));
        equipmentDeviceEntity.setCardinfoIssuingorgan((String) map.get("cardinfoIssuingorgan"));
        equipmentDeviceEntity.setCardinfoPhotopath((String) map.get("cardinfoPhotopath"));
        equipmentDeviceEntity.setCardinfoUsefullife((String) map.get("cardinfoUsefullife"));
        equipmentDeviceEntity.setCardinfoCompareresult((String) map.get("cardinfoCompareresult"));
        equipmentDeviceEntity.setCardinfoId((Long) map.get("cardinfoId"));
        equipmentDeviceEntity.setCardinfoCreatetime((Long) map.get("cardinfoCreatetime"));
        equipmentDeviceEntity.setCardinfoDevicekey((String) map.get("cardinfoDevicekey"));
        equipmentDeviceEntity.setAppId((Long) map.get("appId"));
        equipmentDeviceEntity.setActionId((Long) map.get("actionId"));

        equipmentDeviceEntity.setFaceGuid((String) map.get("faceGuid"));
        equipmentDeviceEntity.setSceneGuid((String) map.get("sceneGuid"));
        equipmentDeviceEntity.setStatus((Long) map.get("status"));
        equipmentDeviceEntity.setCode((String) map.get("code"));
        equipmentDeviceService.save(equipmentDeviceEntity);
        //设备上线
        if (eventCode.equals("100002")) {
            System.out.println("设备上线 设备下线   设备序列号： " + deviceNo + " 状态： 100002");
            OnlineLine(deviceNo, 1);
        }
        //设备下线
        if (eventCode.equals("100003")) {
            System.out.println("设备上线 设备下线   设备序列号： " + deviceNo + " 状态： 100003");
            OnlineLine(deviceNo, 2);
        }
//        设备增删改
//        if (eventCode.equals("100009") && type.equals(1)) {
//            System.out.println("设备增删改   设备序列号： " + deviceNo + " 状态： 100009");
//
//            settingUpdate(deviceNo);
//        }
    }

    /**
     * 设备上线 设备下线
     */
    private void OnlineLine(String deviceNo, int status) {
        System.out.println("设备上线 设备下线   设备序列号： " + deviceNo + " 状态： " + status);
        EquipmentEquipmentEntity one = equipmentEquipmentService.getOneL(deviceNo);
        if (one != null) {
            one.setStatus(status);
        }
        equipmentEquipmentService.updateById(one);
    }

    public R<String> settingUpdate(String deviceNo) throws Exception {
        String url = "/v2/device/setting/update"; // 替换为你要发送请求的URL

        String token = CacheUtil.getValue("authenticationToken");
        if (token == null) {
            return R.error(MessageConstant.TOKEN_ERROR_NULL);
        }
        String response = HttpClientUtil.sendPostRequest(url, ADU(deviceNo), token, PROJECT_GUID);
        return R.success(response, "操作成功");
    }

    /**
     * 设备增删改
     */
    public String ADU(String deviceNo) {
        // 假设 deviceNo 是从某处获取的，这里为了示例，我们给它一个固定值
//        String deviceNo = "yourDeviceNumber"; // 替换为您的 deviceNo

        // 创建 JSON 字符串的各个部分
        String source = "\"source\": \"000000\",";
        String deviceNoPart = "\"deviceNo\": \"" + deviceNo + "\",";
        String deviceConfigsStart = "\"deviceConfigs\": [";
        String deviceConfigsEnd = "]";
        String deviceConfigsInner =
                "{\"key\":\"scrDisplayText2Content\",\"value\":\" 点击上传\"}," +
                        "{\"key\":\"comRecDistModeType\",\"value\":\"2\"}," +
                        "{\"key\":\"comRecRank\",\"value\":\"2\"}," +
                        "{\"key\":\"isShowPersonCount\",\"value\":\"false\"}," +
                        "{\"key\":\"recFailComModeContent\",\"value\":\"识别失败\"}," +
                        "{\"key\":\"recFailDisplayTextContent\",\"value\":\"开门成功\"}," +
                        "{\"key\":\"recFailDisplayTextType\",\"value\":\"100\"}," +
                        "{\"key\":\"recFailTtsModeContent\",\"value\":\"欢迎光临\"}," +
                        "{\"key\":\"recFailTtsModeType\",\"value\":\"100\"}," +
                        "{\"key\":\"recSucComModeContent\",\"value\":\"开门失败\"}," +
                        "{\"key\":\"recSucComModeType\",\"value\":\"2\"}," +
                        "{\"key\":\"recSucDisplayText1Content\",\"value\":\"橙子\"}," +
                        "{\"key\":\"recSucRelayType\",\"value\":\"2\"}," +
                        "{\"key\":\"cardEnable\",\"value\":\"2\"}," +
                        "{\"key\":\"recModePasswordEnable\",\"value\":\"1\"}," +
                        "{\"key\":\"recSucDisplayText2Type\",\"value\":\"100\"}," +
                        "{\"key\":\"recSucDisplayText2Content\",\"value\":\"识别失败\"}," +
                        "{\"key\":\"isShowDeviceKey\",\"value\":\"false\"}," +
                        "{\"key\":\"recSucTtsModeContent\",\"value\":\"识别失败\"}," +
                        "{\"key\":\"recSucTtsModeType\",\"value\":\"100\"}," +
                        "{\"key\":\"recFailRelayType\",\"value\":\"1\"}," +
                        "{\"key\":\"scrDisplayText2Type\",\"value\":\"100\"}";

        // 使用 StringBuilder 构建完整的 JSON 字符串
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.append("{");
        jsonBuilder.append(source);
        jsonBuilder.append(deviceNoPart);
        jsonBuilder.append(deviceConfigsStart);
        jsonBuilder.append(deviceConfigsInner);
        jsonBuilder.append(deviceConfigsEnd);
        jsonBuilder.append("}");

        // 输出或返回生成的 JSON 字符串
        System.out.println(jsonBuilder.toString());

        return jsonBuilder.toString();
    }

    public static void main(String[] args) {
        // 假设 deviceNo 是从某处获取的，这里为了示例，我们给它一个固定值
        String deviceNo = "yourDeviceNumber"; // 替换为您的 deviceNo

        // 创建 JSON 字符串的各个部分
        String source = "\"source\": \"000000\",";
        String deviceNoPart = "\"deviceNo\": \"" + deviceNo + "\",";
        String deviceConfigsStart = "\"deviceConfigs\": [";
        String deviceConfigsEnd = "]";
        String deviceConfigsInner =
                "{\"key\":\"scrDisplayText2Content\",\"value\":\" 点击上传\"}," +
                        "{\"key\":\"comRecDistModeType\",\"value\":\"2\"}," +
                        "{\"key\":\"comRecRank\",\"value\":\"2\"}," +
                        "{\"key\":\"isShowPersonCount\",\"value\":\"false\"}," +
                        "{\"key\":\"recFailComModeContent\",\"value\":\"识别失败\"}," +
                        "{\"key\":\"recFailDisplayTextContent\",\"value\":\"开门成功\"}," +
                        "{\"key\":\"recFailDisplayTextType\",\"value\":\"100\"}," +
                        "{\"key\":\"recFailTtsModeContent\",\"value\":\"欢迎光临\"}," +
                        "{\"key\":\"recFailTtsModeType\",\"value\":\"100\"}," +
                        "{\"key\":\"recSucComModeContent\",\"value\":\"开门失败\"}," +
                        "{\"key\":\"recSucComModeType\",\"value\":\"2\"}," +
                        "{\"key\":\"recSucDisplayText1Content\",\"value\":\"橙子\"}," +
                        "{\"key\":\"recSucRelayType\",\"value\":\"2\"}," +
                        "{\"key\":\"cardEnable\",\"value\":\"2\"}," +
                        "{\"key\":\"recModePasswordEnable\",\"value\":\"1\"}," +
                        "{\"key\":\"recSucDisplayText2Type\",\"value\":\"100\"}," +
                        "{\"key\":\"recSucDisplayText2Content\",\"value\":\"识别失败\"}," +
                        "{\"key\":\"isShowDeviceKey\",\"value\":\"false\"}," +
                        "{\"key\":\"recSucTtsModeContent\",\"value\":\"识别失败\"}," +
                        "{\"key\":\"recSucTtsModeType\",\"value\":\"100\"}," +
                        "{\"key\":\"recFailRelayType\",\"value\":\"1\"}," +
                        "{\"key\":\"scrDisplayText2Type\",\"value\":\"100\"}";

        // 使用 StringBuilder 构建完整的 JSON 字符串
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.append("{");
        jsonBuilder.append(source);
        jsonBuilder.append(deviceNoPart);
        jsonBuilder.append(deviceConfigsStart);
        jsonBuilder.append(deviceConfigsInner);
        jsonBuilder.append(deviceConfigsEnd);
        jsonBuilder.append("}");

        // 输出或返回生成的 JSON 字符串
        System.out.println(jsonBuilder.toString());

    }
}
